package com.bigflexlib.x.flash.utils.Timer
{
	import com.bigflexlib.x.flash.events.ValueChangedEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	

	/**
	 *
	 *  @eventType com.bigflexlib.x.flash.events.ValueChangedEvent.VALUE_CHANGED
	 */
	[Event(name="valueChanged", type="com.bigflexlib.x.flash.events.ValueChangedEvent")]

	
	
	/**
	 * 
	 * An all too common use case in UI development.
	 * 
	 * @author aldo.bucchi@univrz.com
	 * 
	 */
	public class TimeConsolidatedValue extends EventDispatcher
	{
		
		private var timer:Timer;
		
		private var _value:*;
		[Bindable("valueChanged")]
		public function get value( ):*
		{
			return _value;
		}
		
		
		private var nextValue:*;
		
		public function get delay( ):Number{
			return timer.delay;
		}
		public function set delay(v:Number):void{
			timer.delay = v;
		}
		
		
		public function TimeConsolidatedValue( delay:Number=500 )
		{
			timer = new Timer( delay, 1 );	
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, timer_timerComplete);		
		}
		
		public function setValue( newValue:* ):void
		{
			nextValue = newValue;
			timer.reset();
			timer.start();	
		}
		
		/**
		 * Calls setValue() internally, but being a property,
		 * it can be used as data binding target, etc.
		 * 
		 * @param v
		 * 
		 */
		public function set inputValue( v:* ):void{
			setValue( v );
		}
		
				
		
		private function timer_timerComplete( event:TimerEvent ):void
		{
			if ( nextValue === _value )
				return;
			_value = nextValue;
			ValueChangedEvent.dispatch( this, _value );	
		}
		
	}
}